package org.gongzhen.main.UserController;

import org.gongzhen.Result;
import org.gongzhen.User;
import org.gongzhen.main.UserService.UserService;
import org.gongzhen.main.Utils.JwtUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping(value = "/api/auth", produces = MediaType.APPLICATION_JSON_VALUE)
@CrossOrigin(origins = "http://127.0.0.1:5173", allowCredentials = "true")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/login", method = {RequestMethod.GET, RequestMethod.POST})
    public Result login(
            @RequestParam(required = true) String username,
            @RequestParam(required = true) String password) {

        // 验证输入不为空
        if (username == null || username.trim().isEmpty() ||
                password == null || password.trim().isEmpty()) {
            logger.warn("登录尝试：用户名或密码为空");
            return Result.error("用户名和密码不能为空");
        }

        try {
            User user = userService.findByUsername(username);
            if (user == null) {
                logger.info("登录失败：用户不存在 - {}", username);
                return Result.error("用户名或密码错误");
            }

            if (user.getPassword().equals(password)) {
                Map<String, Object> claims = new HashMap<>();
                claims.put("id", user.getId());
                claims.put("username", user.getUsername());

                String token = JwtUtils.generateToken(claims);
                logger.info("用户登录成功：{}", username);

                Map<String, String> response = new HashMap<>();
                response.put("token", token);
                return Result.success(response);
            } else {
                logger.info("登录失败：密码错误 - {}", username);
                return Result.error("用户名或密码错误");
            }
        } catch (Exception e) {
            logger.error("登录过程中发生错误", e);
            return Result.error("登录失败，请稍后重试");
        }
    }
}
